<?php

/**
 * Class home 首页
 */
class home extends Lowxp{
    function index(){
        $this->display_before();
        $tpl = 'index.html';
        $data = array();
        $this->load->model('yunbuy');
        $this->load->model('auction');
        if(STPL == 'mobile'){
            #获取已揭晓
            $sql = "SELECT * FROM ###_yunbuy where luck_code>0 and is_show=1 order by end_time DESC,buy_id DESC LIMIT 4";
            $list = $this->db->select($sql);
            //$list = $this->db->lJoin($list,'yundb','ip,qty,buy_id,goods_name','buy_id','buy_id');
            $list = $this->db->lJoin($list,'goods','id,price','goods_id','id','g_');
            $list = $this->db->lJoin($list,'member','mid,username,nickname,photo','member_id','mid');
            foreach($list as $k=>$v){
                $v = $this->yunbuy->getThumb($v);
                $list[$k] = $v;
            }
            $this->smarty->assign('luck_db', $list);

            #云购列表
            $size = 4;
            $this->smarty->assign('size',$size);

            $orderby = isset($_GET['order'])?$_GET['order']:'ratio';
            $ordersort = isset($_GET['sort'])?$_GET['sort']:'DESC';

            $list = $this->yunbuy->getyunbuy("end_num > 0 AND is_show = 1 AND type=1 ORDER BY $orderby $ordersort",$size,1,"*,buy_num/need_num AS ratio");
            $this->smarty->assign('list',$list);

            #移动端分类
            $this->load->model('mobilecat');
            $mobileCat = $this->mobilecat->select();
            $this->smarty->assign('mobileCat',$mobileCat);

            #判断是否关注
            $subscribe = 1; //0已关注 1未关注
            if($this->is_wechat){
                if(isset($_SESSION['mid'])){
                    $this->load->model('member');
                    $member_info = $this->member->member_info($_SESSION['mid'],'mid,subscribe_time,openid');
                }

                //获取OPENID
                $openid = $member_info ? $member_info['openid'] : '';
                if(empty($openid) && !empty($_SESSION['oauth']['openid'])){
                    $openid = $_SESSION['oauth']['openid'];
                }

                if($openid){
                    if($member_info && !empty($member_info['subscribe_time'])){
                        $subscribe = 0;
                    }else{
                        //未关注进行关注验证
                        $this->load->model('wxapi');
                        $user_info = $this->wxapi->userInfo($openid);

                        if($user_info['subscribe']){
                            $subscribe = 0;
                            if($member_info && empty($member_info['subscribe_time'])){
                                $this->db->update('member',array('subscribe_time' => time()),array('mid'=>$member_info['mid']));
                            }
                        }
                    }
                }

                $this->smarty->assign("subscribe", $subscribe);
            }
        }else{
            #焦点图右侧夺宝推荐位
            $recbuy = $this->yunbuy->getyunbuy("end_num<>0 AND is_show=1 AND posid=1 ORDER BY posid DESC,buy_id DESC",5);
            $recbuy = $this->db->lJoin($recbuy,'goods','id,price','goods_id','id','g_');
            $this->smarty->assign("recbuy",$recbuy);

            #获取会员信息
            if(isset($_SESSION['mid']) && $_SESSION['mid']){
                $this->load->model('member');
                $this->memberinfo = $this->member->member_info($_SESSION['mid']);
                $this->smarty->assign('member',$this->memberinfo);
            }

            #获取已揭晓
            $sql = "SELECT * FROM ###_yunbuy where luck_code>0 and is_show=1 order by end_time DESC,buy_id DESC LIMIT 5";
            $list = $this->db->select($sql);
            $list = $this->db->lJoin($list,'yundb','ip,qty,buy_id,goods_name','buy_id','buy_id','',array('status'=>3));
            $list = $this->db->lJoin($list,'goods','id,price','goods_id','id','g_');
            $list = $this->db->lJoin($list,'member','mid,username,nickname,photo','member_id','mid');
            foreach($list as $k=>$v){
                $new_buy = $this->db->get("SELECT buy_id,qishu FROM ###_yunbuy WHERE sid = '$v[sid]' ORDER BY  buy_id DESC");
                $v['new_buy'] = $new_buy;
                $v = $this->yunbuy->getThumb($v);
                $list[$k] = $v;
            }
            $data['jxdb'] = $list;

            #晒单记录
            $share = $this->yunbuy->getShare("s.is_show>0 AND s.mid<>0 ORDER BY id DESC",12);
            $this->smarty->assign('share',$share);

            //夺宝分类
            $this->load->model('yuncat');
            $yuncat = $this->yuncat->select();

            if(CUR_SKIN == 'theme_01'){
                #获取最新夺宝
                $newyunbuy = $this->yunbuy->getyunbuy("end_num<> 0 AND is_show = 1 ORDER BY buy_id DESC",8);
                $this->smarty->assign("newyunbuy",$newyunbuy);

                #获取楼层商品
                $this->load->model('yuncat');
                foreach($yuncat as $k=>$v){
                    $v['list'] = $this->yunbuy->getyunbuy("end_num<>0 AND is_show=1 AND cid".$this->yuncat->condArrchild($v['id'])." ORDER BY listorders DESC,ratio DESC,buy_id DESC",5,1,"*,buy_num/need_num AS ratio");
                    $yuncat[$k] = $v;
                }
            }else{
                #获取8个进行中夺宝
                $limitnum = 8;
                $yunbuy = $this->yunbuy->getyunbuy("end_num<> 0 AND is_show = 1 ORDER BY listorders DESC,ratio DESC,buy_id DESC",$limitnum,1,"*,buy_num/need_num AS ratio");
                $yunbuy = $this->db->lJoin($yunbuy,'goods','id,price','goods_id','id','g_');
                $this->smarty->assign("yunbuy",$yunbuy);

                #获取开奖列表
                $sql = "SELECT cod,addtime FROM ###_cod ORDER BY id DESC LIMIT 3";
                $res = $this->db->select($sql);
                foreach($res as $k=>$v){
                    $a = substr($v['cod'],0,4);
                    $v['cod'] = str_replace($a,$a.'.',$v['cod']);
                    if($k==0){
                        $data['cod'] = $v;
                    }else{
                        $data['codlist'][] = $v;
                    }
                }

                #获取最新夺宝
                $newyunbuy = $this->yunbuy->getyunbuy("end_num<> 0 AND is_show = 1 AND type = 1 ORDER BY buy_id DESC",10);
                $this->smarty->assign("newyunbuy",$newyunbuy);

                #狗屎运
//                $sql = "select * from ###_yundb where status <> 1 ORDER BY id DESC LIMIT 18";
//                $luck_db = $this->db->select($sql);
//                $luck_db = $this->db->lJoin($luck_db,'yunbuy','buy_id,need_num','buy_id','buy_id');
//                $luck_db = $this->db->lJoin($luck_db,'member','mid,nickname,photo','mid','mid');
                $luck_db = $this->yunbuy->getyunDb("AND d.status <> 1 ORDER BY d.id DESC",18,1);
                $this->smarty->assign('luck_db',$luck_db);
                //print_r('<pre>');var_dump($luck_db);print_r('</pre>');exit;

                #获取8个竞拍推荐商品
                $size = 8;
                $data['indexAuction'] = $this->auction->getList($size,1,0,UNDER_WAY);

                #获取最近的一个即将开始竞拍商品的开始时间
                $sql = "SELECT start_time FROM ###_goods_activity WHERE act_type=0 AND " . $this->auction->status_sql(PRE_START) . " ORDER BY start_time ASC LIMIT 1";
                $data['pre_start_time'] = $this->db->getstr($sql);
                $data['pre_start_time'] = $data['pre_start_time'] - time();

                #最新参拍记录
                $size = 15;
                $data['log'] = $this->auction->logList($size,1,0,0,AllWIN,array(
                    'fields' => 'g.title,g.ext_info,m.photo,m.nickname'
                ));
            }

            $this->smarty->assign('yuncat',$yuncat);
        }

        $this->smarty->assign('data', $data);
        $this->smarty->assign('navMark', 'index');
        $this->smarty->display($tpl);
    }
    /**
     * AJAX 更新夺宝信息
     */
    function update_db(){
        $id = intval($_GET['id']);
        $this->load->model('yunbuy');
        $row = $this->yunbuy->yuninfo($id);
        if(!empty($row)){
            if(!empty($row['wait_time']) && RUN_TIME >= $row['wait_time'] && empty($row['luck_code'])){
                $this->yunbuy->lottery($id);
                echo true;
            }
        }
    }
    /**
     * AJAX获取夺宝单一信息
     */
    function load_db(){
        $id = intval($_GET['id']);
        $this->load->model('yunbuy');
        $this->load->model('member');
        $this->load->model('goods');
        $row = $this->yunbuy->getyunbuy("buy_id = $id");
        $row = $row[0];
        if($row['member_id']){
            $row['luck_member'] = $this->member->member_info($row['member_id']);
            $goods = $this->goods->get($row['goods_id']);
            $row['g_price'] = $goods['price'];
            $this->smarty->assign('m',$row);
            $this->smarty->display('content/windjxajaxindex.html');
        }
    }

    /**
     * 上传图片
     */
    function upload(){
        $file = trim($_POST['name']);
        $this->load->model('upload');
        $thumb = array();

        if(!empty($_POST['width'])&&!empty($_POST['height'])){
            $thumb = array('thumb'=>array('width'=>floor($_POST['width']),'height'=>floor($_POST['height'])));
        }
        echo $this->upload->save_image('upFile',$file,$thumb);
    }

    function fileupload(){
        $this->load->model('upload');
        $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
        $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 1;
        $result = array();
        $allow_type = array('.jpg','.jpeg','.gif','.png');
        //大文件分片上传
        if($chunks>1){
            if (isset($_REQUEST["name"])) {
                $fileName = $_REQUEST["name"];
            } elseif (!empty($_FILES)) {
                $fileName = $_FILES["file"]["name"];
            } else {
                $fileName = uniqid("file_");
            }
            $epos = strrpos($fileName,'.');#点的位置
            $name = substr($fileName,0,$epos);#文件名称
            $ext = strtolower(substr($fileName,$epos));#扩展名
            if(!in_array($ext, $allow_type)){
                //如果不被允许，则直接停止程序运行
                echo json_encode(array('error'=>'请上传图片格式文件'));
                exit;
            }
            //新文件名
//            if($chunk==$chunks-1){
//                $name = $this->upload->random_filename();
//                $_SESSION['filename'] = $name.$ext;
//            }
            $fileName = md5($fileName.$_SESSION['mid']).$ext;

            $targetDir = 'upload'. DIRECTORY_SEPARATOR .'files';
            $uploadDir = 'upload'. DIRECTORY_SEPARATOR .'images'. DIRECTORY_SEPARATOR .'files';
            $cleanupTargetDir = true; // Remove old files
            $maxFileAge = 5 * 3600; // Temp file age in seconds
            $fileName = iconv('UTF-8', 'GB2312', $fileName);//转编码
            $filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;
            $uploadPath = $uploadDir .DIRECTORY_SEPARATOR. $fileName;
            // Remove old temp files
            if ($cleanupTargetDir) {
                if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
                    die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
                }

                while (($file = readdir($dir)) !== false) {
                    $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file;

                    // If temp file is current file proceed to the next
                    if ($tmpfilePath == "{$filePath}_{$chunk}.part" || $tmpfilePath == "{$filePath}_{$chunk}.parttmp") {
                        continue;
                    }

                    // Remove temp file if it is older than the max age and is not the current file
                    if (preg_match('/\.(part|parttmp)$/', $file) && (@filemtime($tmpfilePath) < time() - $maxFileAge)) {
                        @unlink($tmpfilePath);
                    }
                }
                closedir($dir);
            }


// Open temp file
            if (!$out = @fopen("{$filePath}_{$chunk}.parttmp", "wb")) {
                die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
            }

            if (!empty($_FILES)) {
                if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) {
                    die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
                }

                // Read binary input stream and append it to temp file
                if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) {
                    die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                }
            } else {
                if (!$in = @fopen("php://input", "rb")) {
                    die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
                }
            }

            while ($buff = fread($in, 4096)) {
                fwrite($out, $buff);
            }

            @fclose($out);
            @fclose($in);

            rename("{$filePath}_{$chunk}.parttmp", "{$filePath}_{$chunk}.part");

            $index = 0;
            $done = true;
            for( $index = 0; $index < $chunks; $index++ ) {
                if ( !file_exists("{$filePath}_{$index}.part") ) {
                    $done = false;
                    break;
                }
            }
            if ( $done ) {
                if (!$out = @fopen($uploadPath, "wb")) {
                    die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
                }

                if ( flock($out, LOCK_EX) ) {
                    for( $index = 0; $index < $chunks; $index++ ) {
                        if (!$in = @fopen("{$filePath}_{$index}.part", "rb")) {
                            break;
                        }
                        while ($buff = fread($in, 4096)) {
                            fwrite($out, $buff);
                        }

                        @fclose($in);
                        @unlink("{$filePath}_{$index}.part");
                    }

                    flock($out, LOCK_UN);
                }
                @fclose($out);
                $name = $this->upload->random_filename();
                $newname = $uploadDir .DIRECTORY_SEPARATOR.$name.$ext;
                rename($uploadPath,$newname);
                $result['data'] =  '/'.str_replace(DIRECTORY_SEPARATOR,'/',$newname);
            }
        }else{
            $this->load->model('upload');
            $dir = trim($_REQUEST['dir']);
            //创建目录
            static $upDir;
            if(is_null($upDir))$upDir = $this->load->config('picture','image_dir');#保存目录
            $FullDir = $upDir.$dir.'/';
            is_dir($FullDir)||mkdir($FullDir,0777,true);

            $filename = trim($_REQUEST['name']);
            $epos = strrpos($filename,'.');#点的位置
            $name = substr($filename,0,$epos);#文件名称
            $ext = strtolower(substr($filename,$epos));#扩展名

            if(!in_array($ext, $allow_type)){
                //如果不被允许，则直接停止程序运行
                echo json_encode(array('error'=>'请上传图片格式文件'));
                exit;
            }

            //新文件名
            $name = $this->upload->random_filename();
            $savePath = $FullDir.$name.'_src'.$ext;
            $content = file_get_contents('php://input');
            $file = file_put_contents($savePath, $content, true);

            if(!empty($_REQUEST['width'])&&!empty($_REQUEST['height'])){
                $thumb = array('thumb'=>array('width'=>floor($_REQUEST['width']),'height'=>floor($_REQUEST['height'])));
            }

            //生成图片缩略图
            if(is_array($thumb)){
                static $loadedImage;
                if(is_null($loadedImage)){
                    $this->load->library('image',array('ratio'=>true));
                    $loadedImage = true;
                }
                //载入图片.
                $this->image->load_src($savePath);

                foreach($thumb as $size=>$val){
                    if(!isset($val['height'],$val['width']))continue;
                    $widht = $val['width'];
                    $height = $val['height'];
                    $path = $FullDir.$name.'_'.$size.$ext;
                    $this->image->resize($widht, $height, $path, true);
                    $img = str_replace(RootDir.'web/upload/images','',$path);
                    $this->upload->yunsave($img,$dir);
                }
            }

            if(!empty($thumb)){
                $this->upload->rmFile($savePath);
            }else{
                $img = str_replace(RootDir.'web/upload/images','',$savePath);
                $this->upload->yunsave($img,$dir);
            }
            //保存原图
            $result['data'] = empty($thumb) ? str_replace(RootDir.'web','',$savePath) : str_replace(RootDir.'web','',$path);
        }
        echo json_encode($result);
        exit;
    }

    /**
     * AJAX联动菜单
     */
    function chang_parent(){
        $id = (int) $_POST['id'];
        $hidetop = $_POST['hidetop'];
        $field = $_POST['field'];
        $this->load->model('linkage');
        $str = $this->linkage->select_linkage($id,$hidetop,$field,true);
        die($str);
    }

}